//
//  HWItemDetailsViewController.m
//  HappyWeekend
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 com.mjykj.www. All rights reserved.
//

#import "HWItemDetailsViewController.h"
#import "HWItemDetailsModel.h"
#import "HWTuWenView.h"
#import "HWCommentView.h"
#import "HWItemFootView.h"
#import "HWLoginAndRegisterViewController.h"
#import "HWsendCommentsView.h"
typedef void (^BackHeight)(CGFloat height);

@interface HWItemDetailsViewController ()<UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate,UMSocialUIDelegate>

@property (nonatomic, copy) BackHeight backHeighBlock;

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) CGFloat height;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) HWItemHeaderView *headerView;

@property (nonatomic, strong) UIButton *commetingButton;

@property (nonatomic, strong) NSNumber *commentCounts;

@property (nonatomic, strong) HWTuWenView *tuWenView;

@property (nonatomic, strong) NSArray *countArray;

@property (nonatomic, strong) UIView *commetAndPictureView;

@property (nonatomic, strong) NSString *buyUrl;

@property (nonatomic, strong) HWsendCommentsView *sendCommentView;

@end

@implementation HWItemDetailsViewController

- (void)viewDidLoad {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    [self addBar];
    [self addTableVie];
    [self requestDta];
    [self requestDataWithComment];
    [self addCommentButton];
    [self addFootView];
    [self sendComment];
    

}
- (void)requestDta{
   NSString *str = @"http://api.guozhoumoapp.com/v2/items/";
    NSString *url = [NSString stringWithFormat:@"%@%@",str,_itemModel.myID];
    [HWRequestManager requestWithUrl:url parmDic:nil method:GET1 succeedWithData:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSString *detail_html = dic[@"data"][@"detail_html"];
        _commentCounts = dic[@"data"][@"comments_count"];
        _buyUrl = dic[@"data"][@"purchase_url"];
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0 , 0, kScreenWidth,kScreenHeight)];
        _webView.delegate = self;
        // 改变 webview 上图片大小
        NSString *str = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>%@",kScreenWidth - 15, detail_html];
        [_webView loadHTMLString:str baseURL:nil];
        [_tableView reloadData];
    } failedWithError:^(NSError *connectionError) {
        
    }];
}

// 评论数据解析
- (void)requestDataWithComment{
    NSString *url = [NSString stringWithFormat:@"http://api.guozhoumoapp.com/v2/items/%@/comments?limit=20&offset=0",_itemModel.myID];
    [HWRequestManager requestWithUrl:url parmDic:nil method:GET1 succeedWithData:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
       _countArray = dic[@"data"][@"comments"];
        _dataArray = [NSMutableArray array];
        for (NSDictionary *oneDic in _countArray) {
            HWItemDetailsModel *model = [[HWItemDetailsModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_dataArray addObject:model];
        }
    } failedWithError:^(NSError *connectionError) {
        
    }];

}
// 添加 footView
- (void)addFootView{
    HWItemFootView *footView = [[HWItemFootView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49)];
    [footView.loveButton addTarget:self action:@selector(loveButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.buyButton addTarget:self action:@selector(buyButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:footView];
}
// 实现点击方法
- (void)loveButtonClick:(UIButton *)sender{
    HWLoginAndRegisterViewController *logVC = [[HWLoginAndRegisterViewController alloc] init];
    [self.navigationController pushViewController:logVC animated:YES];
//        BOOL islogin = [[HWFileMannager shareManager] isLogin];
//   if (islogin) {
//       NSLog(@"登陆过了");
//   } else {
//       HWLoginAndRegisterViewController *logVC = [[HWLoginAndRegisterViewController alloc] init];
//       [self.navigationController pushViewController:logVC animated:YES];
//    }
   }
- (void)buyButtonClick:(UIButton *)sender{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_buyUrl]];
}
- (void)addTableVie{
    _headerView = [[HWItemHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    _headerView.titleLabel.text = _itemModel.name;
    _headerView.priceLabel.text = [NSString stringWithFormat:@"￥ %@",_itemModel.price];
    _headerView.contentLabel.text = _itemModel.descriptions;
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGRect rect = [_itemModel.descriptions boundingRectWithSize:CGSizeMake(kScreenWidth - 20, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    CGRect temp = _headerView.contentLabel.frame;
    temp.size.height = rect.size.height;
    _headerView.contentLabel.frame = temp;
    _headerView.frame = CGRectMake(0, 0, kScreenWidth, _headerView.contentLabel.bottom);
    if (_itemModel.image_urls.count > 1) {
        _headerView.scrollView.delegate = self;
        _headerView.scrollView.contentOffset = CGPointMake(kScreenWidth, 0);
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 376 * kScreenWidth / 481 - 20, kScreenWidth, 10)];
        _pageControl.numberOfPages = _itemModel.image_urls.count;
        _pageControl.currentPage = 0;
        _pageControl.pageIndicatorTintColor = [UIColor greenColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        // 添加点击事件
        [_pageControl addTarget:self action:@selector(changeValue:) forControlEvents:(UIControlEventValueChanged)];
        for (int i = 0; i < _itemModel.image_urls.count + 1; i ++) {
            _headerView.scrollView.contentSize = CGSizeMake(kScreenWidth * (_itemModel.image_urls.count + 1), 376 * kScreenWidth / 481);
            UIImageView *imageVie = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth * i, 0, kScreenWidth, 376 * kScreenWidth / 481)];
            if (i == 0) {
                [imageVie sd_setImageWithURL:[NSURL URLWithString:_itemModel.image_urls[_itemModel.image_urls.count - 1]] placeholderImage:[UIImage imageNamed:@""]];
            } else {
                [imageVie sd_setImageWithURL:[NSURL URLWithString:_itemModel.image_urls[i - 1]] placeholderImage:[UIImage imageNamed:@""]];
            }
            
            [_headerView.scrollView addSubview:imageVie];
        }
    } else {
        _headerView.scrollView.contentSize = CGSizeMake(kScreenWidth, 376 * kScreenWidth / 481);
        UIImageView *imageVie = [[UIImageView alloc] initWithFrame:CGRectMake(0 , 0, kScreenWidth, 376 * kScreenWidth / 481)];
        [imageVie sd_setImageWithURL:[NSURL URLWithString:_itemModel.image_urls[0]] placeholderImage:[UIImage imageNamed:@""]];
        [_headerView.scrollView addSubview:imageVie];
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 113) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = _headerView;
    [self.view addSubview:_tableView];
    [_headerView addSubview:_pageControl];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
}
// 实现方法
- (void)changeValue:(UIPageControl *)sender{
    NSInteger currentPage = sender.currentPage;
    CGFloat x = (currentPage + 1) * kScreenWidth;
    [_headerView.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}
// 代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat x = scrollView.contentOffset.x;
    if (x < 0) {
        [scrollView setContentOffset:CGPointMake(kScreenWidth * _itemModel.image_urls.count, 0) animated:NO];
    }
    if (x > _itemModel.image_urls.count * kScreenWidth) {
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger page = scrollView.contentOffset.x / kScreenWidth;
    if (page == 0) {
        _pageControl.currentPage = _itemModel.image_urls.count;
    } else {
        _pageControl.currentPage = page - 1;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSString *item = [NSString stringWithFormat:@"评论(%@)",_commentCounts];
    _tuWenView = [[HWTuWenView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    [_tuWenView.commentButton setTitle:item forState:(UIControlStateNormal)];
    [_tuWenView.pictureButton addTarget:self action:@selector(pictureButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_tuWenView.commentButton addTarget:self action:@selector(commentButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
       return _tuWenView;
}
// 添加评论 button
- (void)addCommentButton{
    
    _commetingButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _commetingButton.frame = CGRectMake(kScreenWidth - 60, kScreenHeight - 110, 50, 50);
    _commetingButton.backgroundColor = [UIColor grayColor];
    _commetingButton.layer.masksToBounds = YES;
    _commetingButton.layer.cornerRadius = 25;
    [_commetingButton setBackgroundImage:[UIImage imageNamed:@"iconfont-jilu (1)"] forState:(UIControlStateNormal)];
    _commetingButton.hidden = YES;
    [_commetingButton addTarget:self action:@selector(commetingButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_commetingButton];
}
- (void)commetingButtonClick:(UIButton *)sender{
    _sendCommentView.hidden = NO;
    
    BOOL islogin = [[HWFileMannager shareManager] isLogin];
    if (islogin) {
        NSLog(@"登陆过了");
    } else {
        HWLoginAndRegisterViewController *logVC = [[HWLoginAndRegisterViewController alloc] init];
        [self.navigationController pushViewController:logVC animated:YES];
    }

}
// 评论
- (void)commentButtonClick:(UIButton *)sender{
    UITableViewCell *cell = (UITableViewCell *)[_tableView viewWithTag:20];
    cell.userInteractionEnabled = NO;
    _commetingButton.hidden = NO;
    _tuWenView.cLabel.hidden = NO;
    _tuWenView.pLabel.hidden = YES;
    [_webView removeFromSuperview];
    if (_countArray.count > 0) {
        for (int i = 0; i < _countArray.count; i++) {
            HWCommentView *conmmeView = [[HWCommentView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
            conmmeView.tag = 500 + i;
            NSDictionary *dic = _countArray[i];
            NSDictionary *newDic = dic[@"user"];
            [conmmeView.imageV sd_setImageWithURL:[NSURL URLWithString:newDic[@"avatar_url"]] placeholderImage:[UIImage imageNamed:@""]];
            conmmeView.nameLabel.text = newDic[@"nickname"];
            // 设置时间
             NSString *string = [NSString stringWithFormat:@"%@",dic[@"created_at"]];
            NSInteger sec = [string integerValue];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:sec];
            NSDate *nowTime = [date dateByAddingTimeInterval:28800];
            NSTimeZone *zone = [NSTimeZone timeZoneForSecondsFromGMT:8];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
            [formatter setTimeZone:zone];
            NSString *str = [formatter stringFromDate:nowTime];
            NSString *text = [str substringToIndex:16];
            
            conmmeView.timeLabel.text = text;
           

            if (dic[@"replied_user"] != nil) {
                conmmeView.contentLabel.text = [NSString stringWithFormat:@"回复%@:%@",dic[@"replied_user"][@"nickname"],dic[@"content"]];
            } else {
                conmmeView.contentLabel.text = dic[@"content"];
            }
            
            NSDictionary *oneDic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
            CGRect rect = [conmmeView.contentLabel.text boundingRectWithSize:CGSizeMake(conmmeView.contentLabel.width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:oneDic context:nil];
            CGRect temp = conmmeView.contentLabel.frame;
            temp.size.height = rect.size.height;
            conmmeView.contentLabel.frame = temp;
            conmmeView.lineLabel.frame = CGRectMake(conmmeView.contentLabel.left, conmmeView.contentLabel.bottom + 10,kScreenWidth - conmmeView.contentLabel.left, 1);
            conmmeView.frame = CGRectMake(0, 0, kScreenWidth, conmmeView.lineLabel.bottom);
            [cell addSubview:conmmeView];
               }
        for (int i = 0; i < _countArray.count; i++) {
            if (_countArray.count == 1) {
                HWCommentView *oneView = (HWCommentView *)[cell viewWithTag:500];
                oneView.frame = CGRectMake(0, 0, kScreenWidth, oneView.lineLabel.bottom);
            } else {
                HWCommentView *oneView = (HWCommentView *)[cell viewWithTag:499 + i];
                HWCommentView *nextView = (HWCommentView *)[cell viewWithTag:500 + i];
                nextView.frame = CGRectMake(0, oneView.bottom, kScreenWidth, nextView.lineLabel.bottom);
            }
        }
    
    }
    HWCommentView *view = (HWCommentView *)[cell viewWithTag:_countArray.count + 499];
    CGFloat height = view.bottom + 200;
    _backHeighBlock(height);
    _tuWenView.commentButton.userInteractionEnabled = NO;
}
- (void)pictureButtonClick:(UIButton *)sender{
    _tuWenView.cLabel.hidden = YES;
    _tuWenView.pLabel.hidden = NO;
    UITableViewCell *cell = (UITableViewCell *)[_tableView viewWithTag:20];
    for (int i = 0; i < _countArray.count; i++) {
        HWCommentView *view = (HWCommentView *)[cell viewWithTag:500 + i];
        [view removeFromSuperview];
    }
    [cell addSubview:_webView];
   _tuWenView.commentButton.userInteractionEnabled = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   _backHeighBlock = ^void(CGFloat height){
       _height = height;
       
    };
    return _height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    [cell addSubview:_webView];
    cell.tag = 20;
    return cell;
}
- (void)addBar{
    self.navigationItem.title = @"商品详情";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAction) target:self action:@selector(rightItemClick:)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
// 实现 webView 的代理方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    CGFloat height = [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue];
   // _height = height;
    _backHeighBlock(height);
    // 要把 web 的回弹效果关了
    _webView.scrollView.bounces = NO;
    _webView.frame = CGRectMake(0, 0, kScreenWidth, height);
    [_tableView reloadData];
}
// 实现点击方法
- (void)rightItemClick:(UIBarButtonItem *)item{
    [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToQQ  completion:^(UMSocialResponseEntity *response){
        NSLog(@"SnsInformation is %@",response.data);
    }];
    NSString *str = [NSString stringWithFormat:@"%@%@",_itemModel.name,_itemModel.url];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_itemModel.image_urls[0]]];
    UIImage *image = [UIImage imageWithData:data];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"568be18b67e58e1b05000789"
                                      shareText:str
                                     shareImage:image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToQzone,UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,nil]
                                       delegate:self];


}
// 发送评论
- (void)sendComment{
    _sendCommentView = [[HWsendCommentsView alloc] initWithFrame:CGRectMake(0, kScreenHeight / 2 - 50, kScreenWidth, 60)];
    [_sendCommentView.sendButton setTitle:@"发送" forState:(UIControlStateNormal)];
    [self.view addSubview:_sendCommentView];
    _sendCommentView.commetContentText.delegate = self;
    [_sendCommentView.sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _sendCommentView.hidden = YES;
}
- (void)sendButtonClick:(UIButton *)sender{
    // 创建我们的数据库路径, 同时拼接数据库的名字
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"PKDataBase.db"];
    // 根据路径去创建一个数据库
    [HWFileMannager shareManager].db = [FMDatabase databaseWithPath:path];
    // 调用 open 方打开数据库 成功返回 yes 失败 no
    
    if ([[HWFileMannager shareManager].db open]) {
        NSLog(@"打开成功");
    } else {
        NSLog(@"打开失败");
    }
     FMResultSet *result = [[HWFileMannager shareManager].db executeQuery:@"SELECT * FROM PersonList"];
    HWPersonModel *model = [[HWPersonModel alloc] init];
    while ([result next]) {
        NSString *uID = [result stringForColumn:@"uID"];
        NSString *icon = [result stringForColumn:@"icon"];
        NSString *coverimg = [result stringForColumn:@"coverimg"];
        NSString *uname = [result stringForColumn:@"uname"];
        NSString *auth = [result stringForColumn:@"auth"];
        model.uID = uID;
        model.icon = icon;
        model.coverimg = coverimg;
        model.uname = uname;
        model.auth = auth;
    }
    NSString *str = _sendCommentView.commetContentText.text;
    NSString *content = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    NSString *url = @"http://api2.pianke.me/comment/add";
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"content"] = content;
    parDic[@"auth"] = model.auth;
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"24538A91-BDBB-4437-AEE0-0E24D8BF0D58";
    parDic[@"recid"] = @"";
    parDic[@"reuid"] = @"";
    parDic[@"version"] = @"3.0.6";
    parDic[@"contentid"] = @"568939dc5d7743ce178b45f3";
    [HWRequestManager requestWithUrl:url parmDic:parDic method:POST1 succeedWithData:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSString *str = [NSString stringWithFormat:@"%@",dic[@"result"]];
        if ([str isEqualToString:@"1"]) {
            NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
            parDic[@"auth"] = model.auth;
            parDic[@"client"] = @"1";
            parDic[@"deviceid"] = @"24538A91-BDBB-4437-AEE0-0E24D8BF0D58";
            parDic[@"limit"] = @"10";
            parDic[@"start"] = @"0";
            parDic[@"version"] = @"3.0.6";
            parDic[@"contentid"] = @"568939dc5d7743ce178b45f3";
            [HWRequestManager requestWithUrl:@"http://api2.pianke.me/comment/get" parmDic:parDic method:POST1 succeedWithData:^(NSData *data) {
                NSDictionary *oneDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            } failedWithError:^(NSError *connectionError) {
                
            }];
        }
    } failedWithError:^(NSError *connectionError) {
        
    }];
    _sendCommentView.hidden = YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_sendCommentView.commetContentText resignFirstResponder];
    _sendCommentView.hidden = YES;
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
